﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedeSocial.ViewModels;
using RedeSocial.ViewModels.Interfaces;
using RedeSocial.DataAccess;
using RedeSocial.Validation;
using Telerik.Web.UI;
using RedeSocial.ViewModels.Enums;

namespace RedeSocial.Web.UserControls
{
	public partial class ChangeProfile : BaseUserControl
	{
		#region overrides...
		protected override void CreateViewModel()
		{
			CreateUserViewModel = new CreateUserViewModel()
			{
				DefaultLanguage = Language,
				FluentValidator = new CreateUserValidator((Session["DefaultLanguage"] as Language).Id),
				IsNew = false
			};
			if (!IsPostBack)
			{
				using (var dataContext = new RedeSocialEntities())
				{
					cboCountries.DataTextField = "Name";
					cboCountries.DataValueField = "Id";
					cboCountries.DataSource = dataContext.CountryNames.Where(c => c.Language.Id == CreateUserViewModel.DefaultLanguage.Id).OrderBy(c => c.Name).Select(c => new { Id = c.Country.Id, Name = c.Name, Country = c.Country }).ToList();
					cboCountries.DataBind();
				}
				cboCountries.SelectedValue = User.Country.Id.ToString();
			}
		}
		protected override void BindViewModel()
		{
			CreateUserViewModel.AgreeWithTOS = true;
			CreateUserViewModel.Birthday = rdpBirthday.SelectedDate;
			CreateUserViewModel.ConfirmPassword = txtConfPass.Text.Trim();
			CreateUserViewModel.Email = User.Email;
			CreateUserViewModel.Gender = String.Compare(cboGender.SelectedValue, "1", false) == 0 ? Gender.Male : String.Compare(cboGender.SelectedValue, "2", false) == 0 ? Gender.Female : Gender.Unknown;
			CreateUserViewModel.Name = txtName.Text.Trim();
			CreateUserViewModel.Password = txtPass.Text.Trim();
			if (IsPostBack && cboCountries.SelectedItem != null && (CreateUserViewModel.Country == null || CreateUserViewModel.Country.Id != Convert.ToInt32(cboCountries.SelectedValue)))
			{
				using (var dataContext = new RedeSocialEntities())
				{
					int id = Convert.ToInt32(cboCountries.SelectedValue);
					CreateUserViewModel.Country = dataContext.Countries.Where(c => c.Id == id).FirstOrDefault();
				}
			}
		}
		protected override void BindLabels()
		{
			CreateUserViewModel.DefaultLanguage = Session["DefaultLanguage"] as Language;
			//lblError.Text = ResourceManager.GetResource(Constants.LOGINVIEW_INVALIDUSERMESSAGE, LoginViewModel.DefaultLanguage.Id);
			lblName.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_NAMELABEL, CreateUserViewModel.DefaultLanguage.Id);
			lblGender.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_GENDERLABEL, CreateUserViewModel.DefaultLanguage.Id);
			lblbBirthday.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_BIRTHDAYLABEL, CreateUserViewModel.DefaultLanguage.Id);
			lblPass.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_PASSWORDLABEL, CreateUserViewModel.DefaultLanguage.Id);
			lblConfPass.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_CONFIRMPASSWORDLABEL, CreateUserViewModel.DefaultLanguage.Id);
			lblCountries.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_COUNTRYLABEL, CreateUserViewModel.DefaultLanguage.Id);
			cboItemMen.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_MALELABEL, CreateUserViewModel.DefaultLanguage.Id);
			cboItemWoman.Text = ResourceManager.GetResource(Constants.CREATEUSERVIEW_FEMALELABEL, CreateUserViewModel.DefaultLanguage.Id);

			ValidatorBirthday.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDBIRTHDAYVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
			ValidatorConfirmPassword.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDCONFIRMPASSWORDVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
			ValidatorCountry.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDCOUNTRYVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
			ValidatorGender.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDGENDERVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
			ValidatorName.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDNAMEVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
			ValidatorPassword.ErrorMessage = ResourceManager.GetResource(Constants.CREATEUSERVIEW_INVALIDPASSWORDVALIDATION, CreateUserViewModel.DefaultLanguage.Id);
		}
		#endregion
		#region properties...
		protected CreateUserViewModel CreateUserViewModel
		{
			get
			{
				return ViewModel as CreateUserViewModel;
			}
			set
			{
				ViewModel = value;
			}
		}
		#endregion
		#region event handles...
		protected void Page_Load(object sender, EventArgs e)
		{
			Response.Cache.SetCacheability(HttpCacheability.NoCache);
			lblError.Visible = false;
			if (!IsPostBack)
			{
				txtName.Text = User.Name;
				cboGender.SelectedValue = (User.Gender == (int)Gender.Male) ? "1" : "2";
				if (User.Birthday.HasValue)
					rdpBirthday.SelectedDate = User.Birthday.Value;
				rdpBirthday.MinDate = DateTime.Now.Date.AddYears(-150);
				rdpBirthday.MaxDate = DateTime.Now.Date.AddYears(-10);

			}
		}
		#endregion

		protected void btnSend_Click(object sender, EventArgs e)
		{
			if (CreateUserViewModel.IsValid())
				if (RadUpload1.UploadedFiles.Count > 0)
				{
					ContenType contentType;
					int maleid, femaleid;
					using (var context = new RedeSocialEntities())
					{
						byte[] fileBytes = new byte[RadUpload1.UploadedFiles[0].ContentLength];
						string content = RadUpload1.UploadedFiles[0].ContentType;
						contentType = context.ContenTypes.Where(c => c.Name.Equals(content, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
						if (contentType == null)
							contentType = new ContenType() { Name = RadUpload1.UploadedFiles[0].ContentType };
						if (RadUpload1.UploadedFiles[0].InputStream.Read(fileBytes, 0, fileBytes.Length) > 0)
						{
							maleid = context.Files.Where(f => f.Description.Equals("GenericMan")).Select(f => f.Id).FirstOrDefault();
							femaleid = context.Files.Where(f => f.Description.Equals("GenericWoman")).Select(f => f.Id).FirstOrDefault();

							if (User.File == null || User.File.Id == maleid || User.File.Id == femaleid)
							{
								User.File = new File()
								{
									ContenType = contentType,
									Description = RadUpload1.UploadedFiles[0].FileName.Substring(RadUpload1.UploadedFiles[0].FileName.LastIndexOf('\\') + 1),
									Object = fileBytes
								};
								context.Files.Add(User.File);
							}

							else
								User.File.Object = fileBytes;
						}
						string encPwd = Security.Encrypt(User.Password);
						context.Countries.Attach(CreateUserViewModel.Country);
						User.Birthday = CreateUserViewModel.Birthday;
						User.Country = CreateUserViewModel.Country;
						User.Gender = (int)CreateUserViewModel.Gender;
						User.Name = CreateUserViewModel.Name;
						if (!string.IsNullOrEmpty(CreateUserViewModel.Password))
						{
							User.Password = encPwd;
						}
						context.SaveChanges();
					}
				}
		}
	}
}